<?php
class AttrController extends Controller{
	
	//控制器过滤
	public function filters(){
		return array(
				'accessControl'
		);
	}
	
	public function accessRules(){
		return array(
				array(
						'allow',
						'actions'=>array('add','list','edit','delete'),
						'users'=>array('@')
				),
				array(
						'deny',
						'users'=>array('*')
				)
		);
	}

	/**
	 * 添加属性
	 * @return [type] [description]
	 */
	public function actionAdd(){
		$attrModel = new Attr();
		if(isset($_POST['Attr'])){
			$attrModel->attributes = $_POST['Attr'];
			if($attrModel->save()){
				$this->redirect(array('list'));
			}
		}
		$this->render('add', array('attrModel'=>$attrModel));
	}
	
	public function actionList(){
		
		//获取所有标签
		$attr = Attr::model()->getAttr();
		$this->render('list',array('attr'=>$attr));
	}
	
	public function actionEdit($attrId){
		$attrId = intval($attrId);
		if($attrId <= 0){
			$this->redirect(array('list'));
		}
		$attr = Attr::model()->findByPk($attrId);
		if(isset($_POST['Attr'])){
			$attr->attributes = $_POST['Attr'];
			if($attr->save()){
				$this->redirect(array('list'));
			}
		}
		$this->render('edit', array('attrModel'=>$attr));
	}
	
	public function actionDelete(){
		if(Yii::app()->request->isAjaxRequest){
			$attrId = Yii::app()->request->getPost('attrId');
			
			//删除属性值
			$res1 = Attr::model()->deleteByPk($attrId);
			
			//删除属性文章对应关系
			$res2 = Yii::app()->db->createCommand()->delete('{{article_attr}}', 'attr_id = :attrId', array(':attrId'=>$attrId));
			if($res1 || $res2){
				echo CJSON::encode(array('code'=>1));
			} else {
				echo CJSON::encode(array('code'=>0,'message'=>'删除失败'));
			}
		}
	}
}